import { Graph, Point, Registry } from '@antv/x6';

// 注册自定义锚点、路由等；
export default () => {
  // 设置审批流程节点的锚点位置，将锚点设置到icon的中心位置;
  if (!Registry.NodeAnchor.registry.exist('iconCenter')) {
    Graph.registerAnchor('iconCenter', (view, magnet, ref, args = {}) => {
      const { dx = 24, dy = 0 } = args;
      const bbox = view.getBBoxOfElement(magnet);
      const x = bbox.x + dx;
      // 默认锚点纵坐标在节点的中间位置;
      let y = bbox.y + bbox.height / 2;

      if (dy in args) {
        // 如果设置了纵坐标偏移量，y坐标将相对顶部做偏移设置；
        y = bbox.y + dy;
      }

      return new Point(x, y);
    })
  }

  // 注册最多两条线的自定义路由
  if (!Registry.Router.registry.exist('twoSide')) {
    Graph.registerRouter('twoSide', (vertices, args, view) => {
      const sourcePoint = view?.sourceAnchor;
      const targetPoint = view?.targetAnchor;
      const nodes = view.graph.model.getNodes();

      if(sourcePoint.x === targetPoint.x || sourcePoint.y === targetPoint.y) return vertices;

      let corner = new Point(sourcePoint.x, targetPoint.y);
      const ind = nodes.findIndex((node) => {
        const box = node.getBBox();
        if(view.sourceView?.cell.id === node.id || view.targetView?.cell.id === node.id) {
          return false;
        }

        return (
          corner.x >= box.x &&
          corner.x <= box.x + box.width &&
          corner.y >= box.y &&
          corner.y <= box.y + box.height
        );
      });

      if(ind >= 0){
        corner = new Point(targetPoint.x, sourcePoint.y);
      }

      return [corner, ...vertices];
    })
  }

}
